#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MAX_BUF_SIZE 4096
#define RESPONSE_TEMPLATE "HTTP/1.1 200 OK\r\nServer: CMini\r\nContent-Type: text/html;charset=utf-8\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept\r\nContent-Length: %d\r\n\r\n%s"

void handle_client_request(int clifd) {
    char buf[MAX_BUF_SIZE] = {};

    while (read(clifd, buf, sizeof(buf)) > 0) {
        if (strstr(buf, "exit")) {
            close(clifd);
            return;
        } else if (strstr(buf, "ping")) {
            FILE *fp = popen("ping www.baidu.com", "r");
            if (fp) {
                char bufp[MAX_BUF_SIZE];
                fread(bufp, 1, sizeof(bufp) - 1, fp);
                pclose(fp);

                char response[MAX_BUF_SIZE];
                sprintf(response, RESPONSE_TEMPLATE, strlen(bufp), bufp);
                write(clifd, response, strlen(response) + 1);
            }
        } else {
            char *result = "success";
            char response[MAX_BUF_SIZE];
            sprintf(response, RESPONSE_TEMPLATE, strlen(result), result);
            write(clifd, response, strlen(response) + 1);
        }
    }
}

int main(int argc, char *argv[]) {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return -1;
    }

    struct sockaddr_in addr = {};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(7777);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    socklen_t len = sizeof(addr);

    if (bind(sockfd, (struct sockaddr*)&addr, len) < 0) {
        perror("bind failed");
        return -1;
    }

    if (listen(sockfd, 5) < 0) {
        perror("listen failed");
        return -1;
    }

    for (;;) {
        struct sockaddr_in addrcli = {};
        socklen_t lencli = sizeof(addrcli);
        int clifd = accept(sockfd, (struct sockaddr*)&addrcli, &lencli);
        if (clifd < 0) {
            perror("accept failed");
            continue;
        }

        if (fork() == 0) {
            close(sockfd);  // Child process doesn't need the listening socket
            handle_client_request(clifd);
            close(clifd);   // Close client socket in child process
            return 0;       // Exit child process after handling request
        }

        close(clifd);  // Parent process should close client socket
    }

    close(sockfd);
    return 0;
}